import React from 'react';
import styled from 'styled-components';
const functionMap = new WeakMap();
let count = 1;

const Child = React.memo(({ user, callback }: { user: { name: string; age: number }, callback: () => void }) => {
  console.log('Render Child')
  const styles = {
    color: 'red',
    fontSize: '20px',
  }
  return <div style={styles}>
    <div>{user.name}</div>
    <div>{user.age}</div>
    <button onClick={callback}>callback</button>
  </div>
});
export default function useCallbackComp() {
  // const [num,setNum] = useState('');
  // const handleSetNum = (e: React.ChangeEvent<HTMLInputElement>) => {
  //   setNum(e.target.value);
  // };
  /**
   * useCallback: useCallback 用于优化性能，返回一个记忆化的回调函数，可以减少不必要的重新渲染，也就是说它是用于缓存组件内的函数，避免函数的重复创建
   * 入参：callback：回调函数；deps：依赖项数组，当依赖项发生变化时，回调函数会被重新创建，跟useEffect一样
   * 返回值：返回一个记忆化的回调函数，可以减少函数的创建次数，提高性能
   */
  // const handleSetNum = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
  //   setNum(e.target.value);
  // },[]);
  // if(!functionMap.has(handleSetNum)) {
  //   functionMap.set(handleSetNum,count++);
  // } 
  // console.log('函数id',functionMap.get(handleSetNum));
  const [search, setSearch] = useState('')
  const [user, setUser] = useState({
    name: 'John',
    age: 20
  });
  const childCallback = useCallback(() => {
    console.log('callback 执行了')
  },[]);
  return (
    <Wrapper>
      <div className="useCallbackComp">
        {/* <input type="text" value={num} onChange={handleSetNum} /> */}
        <input type="text" value={search} onChange={e => setSearch(e.target.value)} />
        <Child callback={childCallback} user={user} />
      </div>
    </Wrapper>
  );
}
const Wrapper = styled.div`
  .useCallbackComp {
    color: #000;
  }
`;
